<template>
  <div>
    <van-sticky>
      <van-nav-bar title="黑马头条 - 登录" />
    </van-sticky>
    <van-form @submit="onSubmit" ref="form">
      <van-field
        v-model="user.mobile"
        name="mobile"
        label="手机号"
        placeholder="请输入你的手机号"
        :rules="[
          {
            required: true,
            message: '请输入正确手机号',
            pattern: /^1[3456789]\d{9}$/
          }
        ]"
      />
      <van-field
        v-model="user.code"
        type="text"
        name="code"
        label="验证码"
        placeholder="验证码"
        :rules="[
          { required: true, message: '请填写正确验证码', pattern: /^\d{6}$/ }
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          :loading="isLoading"
          :disabled="isLoading"
          loading-text="登陆中..."
          type="info"
          native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginApi } from '../../api/login'
import { getProfile } from '../../api/user'
// import { setToken } from '../../util/token'
export default {
  data () {
    return {
      isLoading: false,
      user: {
        mobile: '13911112222',
        code: '246810'
      }
    }
  },
  methods: {
    onSubmit () {
      this.$refs.form.validate().then(async () => {
        const { mobile, code } = this.user
        try {
          const res = await loginApi({ mobile, code })
          this.$toast({
            message: '登录成功'
          })
          console.log(res)
          // // 把res中的token信息保存到vuex中
          this.$store.commit('SetTokenInfo', res.data.data)
          // setToken(res.data.data.token)
          const pro = await getProfile()
          console.log(pro)
          this.$store.commit('setUser', pro.data.data)
          this.$store.commit('setLogin', true)
          this.$router.push('/home')
        } catch {
          console.log('服务器异常')
        }
      })
    }
  }
}
</script>

<style scoped></style>
